/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.metadata;

import at.schauer.gregor.vienna.exception.ViennaException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.util.ReflectionUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Gregor Schauer
 */
public class JPAMetadataProvider<T> implements MetadataProvider<T> {
	@Override
	public Object getIdentifier(@Nonnull T obj) {
		Member member = getIdentifierMember(obj.getClass());
		if (member instanceof Method) {
			return ReflectionUtils.invokeMethod((Method) member, obj);
		} else {
			try {
				return FieldUtils.readField((Field) member, obj, true);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public void setIdentifier(@Nonnull T obj, @Nullable Object identifier) {
		Member member = getIdentifierMember(obj.getClass());
		if (member instanceof Method) {
			ReflectionUtils.invokeMethod((Method) member, obj, identifier);
		} else {
			try {
				FieldUtils.writeField((Field) member, obj, identifier, true);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		}
	}

	@Override
	public String getIdentifierName(@Nonnull Class<? extends T> clazz) {
		return getIdentifierMember(clazz).getName();
	}

	@Nonnull
	protected Member getIdentifierMember(@Nonnull Class clazz) {
		try {
			List<Member> members = new ArrayList<Member>(1);
			PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
			for (PropertyDescriptor descriptor : propertyDescriptors) {
				Method readMethod = descriptor.getReadMethod();
				if (readMethod != null && readMethod.isAnnotationPresent(Id.class)) {
					members.add(readMethod);
				} else if (!"class".equals(descriptor.getName())) {
					Field field = ReflectionUtils.findField(clazz, descriptor.getName());
					if (field.isAnnotationPresent(Id.class)) {
						members.add(field);
					}
				}
			}

			if (members.size() == 1) {
				return members.get(0);
			}
		} catch (IntrospectionException e) {
			throw new RuntimeException(e);
		}
		throw new ViennaException();
	}

	@Override
	public boolean isTransientType(@Nonnull Class<? extends T> clazz) {
		return false;
	}

	@Override
	public <M extends AccessibleObject & Member> boolean isTransient(@Nonnull M member) {
		return member.isAnnotationPresent(Transient.class) || Modifier.isTransient(member.getModifiers());
	}

	@Nonnull
	@Override
	public String getEntityName(@Nonnull Class<? extends T> clazz) {
		Entity entity = clazz.getAnnotation(Entity.class);
		return entity != null && !StringUtils.isBlank(entity.name()) ? entity.name() : clazz.getSimpleName();
	}
}
